/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package blms.repository.inmemory;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import blms.domain.User;
import blms.exception.UserDoesNotExistException;
import blms.repository.UserRepository;
import blms.util.BLMSMessages;

/**
 * Simple in-memory repository of users. This implementation may be used to load
 * and store users either in memory.
 * 
 * @author João Arthur
 * @author Jonhnny Weslley
 * @author Thiago Emmanuel
 * @version 1.00, 21/04/2008
 * @since 1.0
 */
public class InMemoryUserRepository extends
		InMemoryRepositoryWithAutoIncrementId<User> implements UserRepository {

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.UserRepository#containsEmail(java.lang.String)
	 */
	public boolean containsEmail(final String email) {
		final Collection<User> users = getAll();
		for (final User user : users) {
			if (user.getEmail().equals(email)) {
				return true;
			}
		}
		return false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.UserRepository#findUserByEmail(java.lang.String)
	 */
	public User findUserByEmail(final String email)
			throws UserDoesNotExistException {
		final Collection<User> users = getAll();
		for (final User user : users) {
			if (user.getEmail().equals(email)) {
				return user;
			}
		}
		throw new UserDoesNotExistException(BLMSMessages.UNKNOWN_USER_MESSAGE);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see blms.repository.UserRepository#findUserByLastName(java.lang.String)
	 */
	public List<String> findUserByLastName(final String lastName)
			throws UserDoesNotExistException {

		final List<String> returnValue = new LinkedList<String>();

		Matcher matcher;
		String userLastName;
		final Collection<User> users = getAll();
		final Pattern p = Pattern.compile(lastName, Pattern.CASE_INSENSITIVE);
		for (final User user : users) {
			userLastName = user.getLastName();
			matcher = p.matcher(userLastName);
			if (matcher.matches()) {
				returnValue.add(userLastName);
			}
		}

		if (returnValue.isEmpty()) {
			throw new UserDoesNotExistException(
					BLMSMessages.COULD_NOT_FIND_USER_MESSAGE + " " + lastName);
		}

		return returnValue;
	}

	@Override
	public void remove(final User user) {
		super.remove(user);
		// FIXME remove user references from leagues
	}

}
